package com.billing.gwt.server;

import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.springframework.stereotype.Controller;
import org.springframework.web.client.RestTemplate;

import com.billing.gwt.client.BillingRPCService;
import com.billing.gwt.shared.BillingEntry;
import com.billing.service.rest.JSONBillingEntry;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@Controller
@SuppressWarnings("serial")
public class BillingRPCServiceImpl extends RemoteServiceServlet implements
		BillingRPCService {

	private static final String BASE_URL = "http://localhost:8080/rest-service/billing/rest/";

	@Override
	public List<BillingEntry> getBillingEntries() {
		
		List<BillingEntry>  toReturn = new ArrayList<BillingEntry>();
		boolean debug = true;
		
		
		// TODO Change this for a debug implementation and inject it
		if (debug){

			for (int id = 0; id < 100; id++){
				
				  BillingEntry contact = new BillingEntry();
				  contact.setDescription("Descripcion de la entrada: " + id);
				  contact.setPayer(UUID.randomUUID().toString().substring(0,10));
				  contact.setId(new Long(id));
				  contact.setAmount(id / 0.23);
				  contact.setExecutionDate(new Date());
				  toReturn.add(contact);
				  
		  }
		}
		else {
			RestTemplate restTemplate = new RestTemplate();

			
			try {
				
				String url = BASE_URL + "billingentry/list";
				JSONBillingEntry[] billingEntries = restTemplate.getForObject(url, JSONBillingEntry[].class);
				
				for (JSONBillingEntry jsonEntry : billingEntries){
					if (jsonEntry != null){
						toReturn.add(convertFromJSON(jsonEntry));
					}
				}
				
				
			}
			catch (Exception ex){
				BillingEntry entry = new BillingEntry();
				entry.setDescription(ex.getClass().getName() + ex.getMessage());
				try {
					ex.printStackTrace(new PrintWriter("errorGWT.txt"));
				} catch (FileNotFoundException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				toReturn.add(entry);
			}
			
		}
	
		
		return toReturn;
	}

	private BillingEntry convertFromJSON(JSONBillingEntry jsonEntry) {
		
		BillingEntry toReturn = new BillingEntry();
		toReturn.setId(jsonEntry.getId());
		toReturn.setDescription(jsonEntry.getDescription());
		toReturn.setExecutionDate(jsonEntry.getExecutionDate());
		toReturn.setAmount(jsonEntry.getAmount());
		return toReturn;
	}


}
